package com.liuya.safe.policy.controller;

import com.liuya.base.BaseController;
import com.liuya.common.SpringUtils;
import com.liuya.common.TypeParseUtil;
import com.liuya.common.Util;
import com.liuya.safe.model.SafeUser;
import com.liuya.safe.user.service.UserManagerService;

import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractTestController extends BaseController {

    public Map buildTestContext(HttpServletRequest req, String[] testContextFields) throws ParseException {
        Map ctx = null;
        if (testContextFields.length > 0) {
            ctx = new HashMap();

            for (int i = 0; i < testContextFields.length; i++) {
                String field = testContextFields[i];
                String rawValue = req.getParameter("ctx" + field);
                String fieldType = req.getParameter("ctx" + field + "type");

                Object value = TypeParseUtil.parse(rawValue, fieldType);
                ctx.put(field, value);
            }
        }

        return ctx;
    }

    public Object buildTestBusinessData(HttpServletRequest req, String[] testBusinessDataFields) throws ParseException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        Object bdData = null;
        Class bdClazz = null;

        if (testBusinessDataFields.length > 0) {
            String bdClass = req.getParameter("bdClass");
            bdClazz = Class.forName(bdClass);
            bdData = bdClazz.newInstance();
        }

        for (int i = 0; i < testBusinessDataFields.length; i++) {
            String field = testBusinessDataFields[i];
            String rawValue = req.getParameter("bd" + field);
            String fieldType = req.getParameter("bd" + field + "type");

            Object value = TypeParseUtil.parse(rawValue, fieldType);

            Util.setJavabeanAttribute(bdData, field, fieldType, value);
        }
        return bdData;
    }

    public SafeUser buildTestUser(HttpServletRequest req, boolean testUserNeeded) {
        SafeUser testUser = null;
        if (testUserNeeded) {
            String strUserId = req.getParameter("userId");
//            Object userId = AuthUtil.convertUserId(req, strUserId);
//            testUser = new SafeUser();
//            testUser.setId(strUserId);

            UserManagerService userMng = (UserManagerService) SpringUtils.getBean("userManagerService");
            testUser = userMng.selectById(strUserId);
        }
        return testUser;
    }
}